package com.dict.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dict.listener.ExeclListener;
import com.dict.pojo.Dict;
import com.dict.pojo.ExcelDTO;
import com.dict.service.DictService;
import com.dict.mapper.DictMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author 宋伟宁
* @description 针对表【dict(数据字典)】的数据库操作Service实现
* @createDate 2024-03-06 14:59:30
*/
@Service
@Transactional(rollbackFor = RuntimeException.class)
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict>
    implements DictService{

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void importData(InputStream inputStream) {
        log.info("开始导入数据！");
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        EasyExcel.read(inputStream, ExcelDTO.class,
                new ExeclListener(baseMapper)).sheet().doRead();
        log.info("导入数据完成！");
    }
    @Override
    public List<ExcelDTO> listDictData() {
        List<Dict> dictList = baseMapper.selectList(null);
        //创建ExcelDTO列表，将Dict列表转换成ExcelDictDTO列表
        ArrayList<ExcelDTO> excelDictDTOList = new ArrayList<>(dictList.size());
        dictList.forEach(dict -> {
            ExcelDTO excelDictDTO = new ExcelDTO();
            //将Dict对象转换成ExcelDTO对象
            BeanUtils.copyProperties(dict, excelDictDTO);
            excelDictDTOList.add(excelDictDTO);
        });
        return excelDictDTOList;
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {

//        //先查询redis中是否存在数据列表
//        List<Dict> dictList = null;
//        try {
//            dictList = (List<Dict>)redisTemplate.opsForValue().get("srb:core:dictList:" + parentId);
//
//            if(dictList != null){
//                log.info("从redis中取值");
//                return dictList;
//            }
//
//        } catch (Exception e) {
//
//            log.error("redis服务器异常：" + ExceptionUtils.getStackTrace(e));//此处不抛出异常，继续执行后面的代码
//
//        }
//
//
//        log.info("从数据库中取值");
//
//        dictList = baseMapper.selectList(new QueryWrapper<Dict>().eq("parent_id", parentId));
//
//        dictList.forEach(dict -> {
//
//            //如果有子节点，则是非叶子节点
//            boolean hasChildren = this.hasChildren(dict.getId());
//           // dict.setHasChildren(hasChildren);
//
//        });
//
//
//        //将数据存入redis
//
//        try {
//
//            redisTemplate.opsForValue().set("srb:core:dictList:" + parentId, dictList, 5, TimeUnit.MINUTES);
//            log.info("数据存入redis");
//        } catch (Exception e) {
//            log.error("redis服务器异常：" + ExceptionUtils.getStackTrace(e));//此处不抛出异常，继续执行后面的代码
//        }
//        return dictList;
        QueryWrapper<Dict> queryWrapper =new QueryWrapper<>();
        queryWrapper.isNull("value").isNotNull("dict_code")
                .gt("parent_id",0);
        List<Dict> dicts= baseMapper.selectList(queryWrapper);
        return  dicts;
    }

    @Override
    public Boolean checkDictByName(String name) {
        QueryWrapper<Dict> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("name", name);
        Long count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }

    @Resource
    private DictMapper dictMapper;
    @Override
    public Boolean addDict(Long pid,String name) {
        //判断是否是根据节
        Dict dict= new Dict();
        if( pid == null || pid == 0) {
            dict.setParentId(1L);
        }else{
            dict.setParentId(pid);
        }

            dict.setName(name);
           this.baseMapper.insert(dict);
           //清空缓存

        return true;
    }

    @Override
    public List<Dict> selectAll() {
        return this.dictMapper.selectAll(0);
    }

    /**
     * 判断是否有子节点
     * @param id
     * @return
     */
    private boolean hasChildren(Long id) {

        return false;
    }
}




